package com.doubao.user.controller;

import com.doubao.common.result.Result;
import com.doubao.user.constant.UserConstant;
import com.doubao.user.dto.VipInfoDTO;
import com.doubao.user.dto.request.UserInfoUpdateRequest;
import com.doubao.user.dto.request.UserPasswordUpdateRequest;
import com.doubao.user.dto.response.UserInfoResponse;
import com.doubao.user.dto.response.UserStatisticsResponse;
import com.doubao.user.entity.User;
import com.doubao.user.security.UserContext;
import com.doubao.user.service.UserService;
import com.doubao.user.service.UserStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户管理相关接口")
@Slf4j  // 添加这个注解来使用日志
public class UserController {

    private final UserService userService;
    private final UserStatisticsService userStatisticsService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的基本信息")
    public Result<UserInfoResponse> getCurrentUserInfo() {
        return Result.success(userService.getCurrentUserInfo());
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/info/{userId}")
    @Operation(summary = "根据ID获取用户信息", description = "根据用户ID获取用户信息")
    public Result<UserInfoResponse> getUserInfoById(@PathVariable("userId") Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        UserInfoResponse response = new UserInfoResponse();
        org.springframework.beans.BeanUtils.copyProperties(user, response);

        // 判断是否绑定了微信 - 使用user表中的字段
        boolean isWechatBound = StringUtils.isNotBlank(user.getUnionid())
                || StringUtils.isNotBlank(user.getMiniappOpenid())
                || StringUtils.isNotBlank(user.getOfficialOpenid())
                || StringUtils.isNotBlank(user.getWebOpenid())
                || StringUtils.isNotBlank(user.getAppOpenid());

        response.setWechatBound(isWechatBound);

        return Result.success(response);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    @Operation(summary = "更新用户信息", description = "更新当前登录用户的基本信息")
    public Result<Void> updateUserInfo(@Valid @RequestBody UserInfoUpdateRequest request) {
        return userService.updateUserInfo(request);
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    @Operation(summary = "修改密码", description = "修改当前登录用户的密码")
    public Result<Void> updatePassword(@Valid @RequestBody UserPasswordUpdateRequest request) {
        return userService.updatePassword(request);
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取用户统计信息", description = "获取当前登录用户的统计信息")
    public Result<UserStatisticsResponse> getUserStatistics() {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        return Result.success(userStatisticsService.getUserStatistics(userInfo.getId()));
    }

    /**
     * 检查用户今日token是否超限
     */
    @GetMapping("/token/check")
    @Operation(summary = "检查用户今日token是否超限", description = "检查当前登录用户今日token是否已达到上限")
    public Result<Boolean> checkTokenLimit() {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        boolean exceeded = userService.isTokenLimitExceeded(userInfo.getId());
        return Result.success(exceeded);
    }

    /**
     * 获取用户今日可用token数量
     */
    @GetMapping("/token/available")
    @Operation(summary = "获取用户今日可用token数量", description = "获取当前登录用户今日可用的token数量")
    public Result<Integer> getAvailableTokens() {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        int availableTokens = userService.getAvailableTokens(userInfo.getId());
        return Result.success(availableTokens);
    }

    /**
     * 获取用户token使用情况
     */
    @GetMapping("/daily-token-usage")
    @Operation(summary = "获取用户token使用情况", description = "获取当前登录用户token的使用情况及限制")
    public Result<Map<String, Object>> getDailyTokenUsage() {
        // 检查用户是否已登录
        if (!UserContext.isUserLoggedIn()) {
            log.warn("用户未登录，无法获取token使用情况");
            return Result.failed("用户未登录");
        }

        try {
            Long userId = UserContext.getUserId();
            UserInfoResponse userInfo = userService.getCurrentUserInfo();

            // 从User对象直接获取总量数据
            User user = userService.getUserById(userId);
            Long totalTokensUsed = user.getTotalTokensUsed();
            Integer totalTokensBalance = user.getTotalTokensBalance();

            if (totalTokensUsed == null) {
                totalTokensUsed = 0L;
            }

            if (totalTokensBalance == null) {
                totalTokensBalance = UserConstant.DEFAULT_DAILY_TOKENS_LIMIT;
            }

            Map<String, Object> result = new HashMap<>();
            result.put("totalTokensUsed", totalTokensUsed);
            result.put("totalTokensBalance", totalTokensBalance);

            // 为了保持兼容性，仍然保留原来的字段
            result.put("dailyUsed", 0);
            result.put("limit", totalTokensBalance);

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户token使用情况失败", e);
            return Result.failed("获取token使用情况失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check/username/{username}")
    @Operation(summary = "检查用户名是否存在", description = "检查指定的用户名是否已被注册")
    public Result<Boolean> checkUsername(@PathVariable String username) {
        return Result.success(userService.isUsernameExists(username));
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check/phone/{phone}")
    @Operation(summary = "检查手机号是否存在", description = "检查指定的手机号是否已被注册")
    public Result<Boolean> checkPhone(@PathVariable String phone) {
        return Result.success(userService.isPhoneExists(phone));
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check/email/{email}")
    @Operation(summary = "检查邮箱是否存在", description = "检查指定的邮箱是否已被注册")
    public Result<Boolean> checkEmail(@PathVariable String email) {
        return Result.success(userService.isEmailExists(email));
    }

    /**
     * 获取默认的Token使用情况
     */
    @GetMapping("/token/default")
    @Operation(summary = "获取默认Token使用情况", description = "当用户未登录时返回默认Token使用数据")
    public Result<Map<String, Object>> getDefaultTokenUsage() {
        Map<String, Object> result = new HashMap<>();
        result.put("dailyUsed", 0);
        result.put("limit", UserConstant.DEFAULT_DAILY_TOKENS_LIMIT);
        result.put("isDefault", true);

        return Result.success(result);
    }

    /**
     * 获取用户VIP信息
     *
     * @param userId 用户ID（从请求头获取）
     * @return VIP信息
     */
    @GetMapping("/vip-info")
    @Operation(summary = "获取用户VIP信息", description = "获取当前用户的VIP会员信息")
    public Result<VipInfoDTO> getVipInfo(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        log.info("获取用户VIP信息: userId={}", userId);

        if (userId == null) {
            log.warn("用户未登录，无法获取VIP信息");
            return Result.failed("用户未登录");
        }

        try {
            VipInfoDTO vipInfo = userService.getUserVipInfo(userId);
            log.info("获取VIP信息成功: userId={}, vipInfo={}", userId, vipInfo);
            return Result.success(vipInfo);
        } catch (Exception e) {
            log.error("获取用户VIP信息异常: userId={}", userId, e);
            return Result.failed("获取VIP信息失败: " + e.getMessage());
        }
    }
}
